<template>
  <div class="form">
    <el-form>
      <div class="form-header">
        <el-row>
          <el-col :span="10">
            <span>寄件时间：</span>
            <el-date-picker
              v-model="formModel.datetime"
              type="daterange"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              prop=""
              size="small"
              clearable
              :default-time="['00:00:00', '23:59:59']"
              value-format="timestamp"
            ></el-date-picker>
          </el-col>
          <el-col :span="10" :offset="2">
            <span>快递公司：</span>
            <el-select size="small" v-model="formModel.companyCode" placeholder="请选择快递公司" multiple>
              <el-option
                v-for="item in companyList"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div class="form-main" v-show="isShow">
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">姓名</div>
            <div class="form-item-input">
              <el-input
                v-model.trim="formModel.name.value"
                size="small"
                type="text"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入20个"
                @blur="onInputBlurOrFocus('name')"
              ></el-input>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.name.group">
                <el-checkbox label="send">寄件姓名</el-checkbox>
                <el-checkbox label="recv">收件姓名</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">电话</div>
            <div class="form-item-input">
              <el-input
                v-model="formModel.phone.value"
                size="small"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入200个"
                @blur="onInputBlurOrFocus('phone')"
              ></el-input>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.phone.group">
                <el-checkbox label="send">寄件电话</el-checkbox>
                <el-checkbox label="recv">收件电话</el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="form-item-excel">
              <a href="/template/template.xlsx" download="template.xlsx">下载excel模板</a>
              <a href="/template/template.txt" download="template.txt">下载txt模板</a>
              <uploadExcel @callback="setExportExcelData"></uploadExcel>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row" v-for="(item, index) in formModel.addr.value" :key="index">
            <div class="form-item-label">地区</div>
            <div class="form-item-input">
              <el-cascader
                :options="chinaData"
                :props="{ checkStrictly: true, value: 'label' }"
                clearable
                v-model="formModel.addr.value[index].value"
                size="small"
                placeholder="请选择地区"
              ></el-cascader>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.addr.group" v-if="index === 0">
                <el-checkbox label="send">寄件地址</el-checkbox>
                <el-checkbox label="recv">收件地址</el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="form-item-button">
              <el-button type="primary" size="small" v-if="index === 0" @click="addAddr">添加</el-button>
              <el-button type="danger" size="small" v-else @click="delAddr(index)">删除</el-button>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row" v-for="(item, index) in formModel.addrKeyword.value" :key="index">
            <div class="form-item-label">地址关键词</div>
            <div class="form-item-input">
              <el-input
                size="small"
                v-model="formModel.addrKeyword.value[index]"
                placeholder="请输入地址关键词"
              ></el-input>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.addrKeyword.group" v-if="index === 0">
                <el-checkbox label="send">寄件地址</el-checkbox>
                <el-checkbox label="recv">收件地址</el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="form-item-button">
              <el-button type="primary" size="small" v-if="index === 0" @click="addAddrKeyword">添加</el-button>
              <el-button type="danger" size="small" v-else @click="delAddrKeyword(index)">删除</el-button>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row" v-for="(item, index) in formModel.direction" :key="index">
            <div class="form-item-label">流向</div>
            <div class="form-item-direction">
              <div class="direction-item">
                <el-cascader
                  :options="chinaData"
                  :props="{ checkStrictly: true, value: 'label' }"
                  clearable
                  v-model="formModel.direction[index].outflux.value"
                  size="small"
                  placeholder="请选择地区"
                ></el-cascader>
              </div>
              <div class="direction-item">
                <el-input
                  v-model="formModel.direction[index].outflux.addrKeyword"
                  placeholder="请输入地址关键词"
                  size="small"
                ></el-input>
              </div>
              <div class="direction-separator"></div>
              <div class="direction-item">
                <el-cascader
                  :options="chinaData"
                  :props="{ checkStrictly: true, value: 'label' }"
                  clearable
                  v-model="formModel.direction[index].influx.value"
                  size="small"
                  placeholder="请选择地区"
                ></el-cascader>
              </div>
              <div class="direction-item">
                <el-input
                  v-model="formModel.direction[index].influx.addrKeyword"
                  placeholder="请输入地址关键词"
                  size="small"
                ></el-input>
              </div>
            </div>
            <div class="form-item-button">
              <el-button type="primary" size="small" v-if="index === 0" @click="addDirection">添加</el-button>
              <el-button type="danger" size="small" v-else @click="delDirection(index)">删除</el-button>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">运单号</div>
            <div class="form-item-input">
              <el-input
                v-model="formModel.expressNo"
                size="small"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入20个"
                @blur="onInputBlurOrFocus('expressNo')"
              ></el-input>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">托寄物描述</div>
            <div class="form-item-input">
              <el-input
                v-model="formModel.expressGoodsName"
                size="small"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入10个"
                @blur="onInputBlurOrFocus('expressGoodsName')"
              ></el-input>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">实际重量</div>
            <div class="form-item-input">
              <div class="goods-weight">
                <el-input size="small" v-model="formModel.expressGoodsWeight.start" placeholder="请输入"></el-input>
                <span class="weight-separator">-</span>
                <el-input size="small" v-model="formModel.expressGoodsWeight.end" placeholder="请输入"></el-input>
                <span class="weight-unit">kg</span>
              </div>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">网点代码</div>
            <div class="form-item-input">
              <el-input
                v-model="formModel.placeCode.value"
                size="small"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入20个"
                @blur="onInputBlurOrFocus('placeCode')"
              ></el-input>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.placeCode.group">
                <el-checkbox label="send">寄件</el-checkbox>
                <el-checkbox label="recv">收件</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-row">
            <div class="form-item-label">城市区号</div>
            <div class="form-item-input">
              <el-input
                v-model="formModel.expressNo"
                size="small"
                clearable
                placeholder="输入多个时，请用逗号分隔，最多可输入20个"
                @blur="onInputBlurOrFocus('cityCode')"
              ></el-input>
            </div>
            <div class="form-item-checked">
              <el-checkbox-group v-model="formModel.cityCode.group">
                <el-checkbox label="send">寄件</el-checkbox>
                <el-checkbox label="recv">收件</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div class="form-submit">
        <el-button type="primary" size="small" @click="getSubmit">查询</el-button>
        <el-button type="info" size="small" @click="reset">重置</el-button>
        <el-button type="text" size="small" @click="isShow = !isShow">收起</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import extend from 'extend'
import chinaData from '@a/data/chinaData.json'
import { AccountApi } from '@/api'
import uploadExcel from '@c/UploadExcel'

const originModel = {
  // "pageSize": 10,  //每页大小
  // "pageNum": 1,    //页码,从1开始
  // "startTime": 1606630594000,
  // "endTime": 1637907394000,
  dateTime: null,
  companyCode: null, //快递公司，需大数据侧提供字典后根据字典传值
  name: {
    //姓名
    value: '',
    group: ['send', 'recv'],
  },
  phone: {
    //电话
    value: '',
    group: ['send', 'recv'],
  },
  expressNo: '', //运单号
  expressGoodsName: '', //托寄物描述
  expressGoodsWeight: {
    //实际重量
    start: '',
    end: '',
  },
  placeCode: {
    //网点代码
    value: '',
    group: ['send', 'recv'],
  },
  cityCode: {
    //城市区号
    value: '',
    group: ['send', 'recv'],
  },
  addr: {
    //地区
    value: [
      {
        value: '',
        // province: '', //省份
        // city: '',  //城市
        // area: ''  //区县
      },
    ],
    group: ['send', 'recv'],
  },
  addrKeyword: {
    //地址关键词
    value: [''],
    group: ['send', 'recv'],
  },
  direction: [
    //流向
    {
      outflux: {
        //流出方，即寄件方
        addrKeyword: '',
        value: '',
      },
      influx: {
        //流入方，即收件方
        addrKeyword: '',
        value: '',
      },
    },
  ],
}

export default {
  components: {
    uploadExcel,
  },
  data() {
    return {
      chinaData,
      companyList: [],
      formModel: extend(true, {}, originModel),
      isShow: true,
    }
  },
  created() {
    let companyList = []
    AccountApi.getCompanyCodeInfo().then(res => {
      Object.keys(res).forEach(item => {
        companyList.push({
          value: item,
          label: res[item],
        })
      })
      this.companyList = companyList
    })
  },
  methods: {
    getSubmit() {
      let formModel = extend(true, {}, this.formModel)
      if (formModel.name.value) {
        let maxLen = 20
        if (formModel.name.value.split(',').length > maxLen) {
          return this.$message.error(`姓名最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.name
      }
      if (formModel.phone.value) {
        let maxLen = 200
        if (formModel.phone.value.split(',').length > maxLen) {
          return this.$message.error(`电话最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.phone
      }
      if (formModel.expressNo) {
        let maxLen = 20
        if (formModel.expressNo.split(',').length > maxLen) {
          return this.$message.error(`运单号最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.expressNo
      }
      if (formModel.expressGoodsName) {
        let maxLen = 10
        if (formModel.expressGoodsName.split(',').length > maxLen) {
          return this.$message.error(`托寄物描述最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.expressGoodsName
      }
      if (formModel.placeCode.value) {
        let maxLen = 20
        if (formModel.placeCode.value.split(',').length > maxLen) {
          return this.$message.error(`网点代码最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.placeCode
      }
      if (formModel.cityCode.value.length) {
        let maxLen = 20
        if (formModel.cityCode.value.split(',').length > maxLen) {
          return this.$message.error(`城市代码最多可以输入${maxLen}个`)
        }
      } else {
        delete formModel.cityCode
      }
      for (let i = 0; i < formModel.addr.value.length; i++) {
        if (!formModel.addr.value[i].value || !formModel.addr.value[i].value.length) {
          formModel.addr.value.splice(i, 1)
          i--
        } else {
          formModel.addr.value[i] = {
            province: formModel.addr.value[i].value[0] || '',
            city: formModel.addr.value[i].value[1] || '',
            area: formModel.addr.value[i].value[2] || '',
          }
        }
      }
      if (!formModel.addr.value.length) {
        delete formModel.addr
      }
      for (let i = 0; i < formModel.direction.length; i++) {
        if (
          !formModel.direction[i].outflux.value ||
          !formModel.direction[i].outflux.value.length ||
          !formModel.direction[i].influx.value ||
          !formModel.direction[i].influx.value.length
        ) {
          formModel.direction.splice(i, 1)
          i--
        } else {
          formModel.direction[i].outflux.value = {
            province: formModel.direction[i].outflux.value[0] || '',
            city: formModel.direction[i].outflux.value[1] || '',
            area: formModel.direction[i].outflux.value[2] || '',
          }
          formModel.direction[i].influx.value = {
            province: formModel.direction[i].influx.value[0] || '',
            city: formModel.direction[i].influx.value[1] || '',
            area: formModel.direction[i].influx.value[2] || '',
          }
        }
      }
      if (!formModel.direction.length) {
        delete formModel.direction
      }
      if (formModel.addrKeyword.value.length === 1 && !formModel.addrKeyword.value[0].length) {
        delete formModel.addrKeyword
      }
      if (formModel.companyCode && formModel.companyCode.length) {
        formModel.companyCode = formModel.companyCode.join(',')
      } else {
        delete formModel.companyCode
      }
      if (formModel.dateTime) {
        formModel.startTime = formModel.dateTime[0]
        formModel.endTime = formModel.dateTime[1]
      } else {
        delete formModel.dateTime
      }
      if (!formModel.expressGoodsWeight.start.length && !formModel.expressGoodsWeight.end.length) {
        delete formModel.expressGoodsWeight
      }
      this.$emit('getFormData', formModel)
    },
    reset() {
      this.formModel = extend(true, {}, originModel)
    },
    addAddr() {
      this.formModel.addr.value.push({})
    },
    delAddr(index) {
      this.formModel.addr.value.splice(index, 1)
    },
    addAddrKeyword() {
      this.formModel.addrKeyword.value.push('')
    },
    delAddrKeyword(index) {
      this.formModel.addrKeyword.value.splice(index, 1)
    },
    addDirection() {
      this.formModel.direction.push({
        outflux: {},
        influx: {},
      })
    },
    delDirection(index) {
      this.formModel.direction.splice(index, 1)
    },
    onInputBlurOrFocus(key) {
      if (key === 'expressNo' || key === 'expressGoodsName') {
        let val = this.regexpValue(this.formModel[key])
        this.$set(this.formModel, key, val)
      } else {
        let val = this.regexpValue(this.formModel[key].value)
        this.$set(this.formModel[key], 'value', val)
      }
    },
    regexpValue(val) {
      if (!val) return ''
      return val
        .replace(/，/g, ',')
        .replace(/,+/g, ',')
        .replace(/(^,|,$)/g, '')
    },
    setExportExcelData(data) {
      if (!data.length) return
      this.formModel.phone.value = data
        .slice(0, 500)
        .join(',')
        .replace(/[\s\r\n\r]+/g, '')
    },
  },
}
</script>
<style lang="less" scoped>
.form {
  .form-header,
  .form-main {
    padding: 15px;
    margin-bottom: 10px;
    background-color: #222336;
  }
  .form-main {
    max-height: 600px;
    padding: 0px 0;
    margin-bottom: 15px;
    background-color: #28293e;
    overflow-y: auto;
    .form-item {
      &:hover {
        background-color: #32354d;
      }
      .form-item-row {
        display: flex;
        align-items: center;
        padding: 10px 15px;
        border-bottom: 1px solid #222336;
        .form-item-label {
          width: 120px;
          color: #8282a6;
        }
        .form-item-input {
          width: 30%;
          .goods-weight {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            position: relative;
            .el-input {
              width: 45%;
            }
            .weight-separator {
              width: 10%;
              text-align: center;
            }
            .weight-unit {
              position: absolute;
              right: -30px;
              width: 25px;
            }
          }
        }
        .form-item-checked {
          margin-left: 80px;
        }
        .form-item-excel {
          display: flex;
          font-size: 14px;
          margin-left: 80px;
          a {
            color: #409eff;
            white-space: nowrap;
            margin-right: 20px;
          }
        }
        .form-item-button {
          flex: 1;
          text-align: right;
        }
        .form-item-direction {
          display: flex;
          width: 63%;
          .direction-item {
            width: 25%;
            & + .direction-item {
              margin-left: 15px;
            }
          }
          .direction-separator {
            width: 30px;
            margin: 0 15px;
            background: url('~@a/img/icon-arrow.png') center center/100% no-repeat;
          }
        }
      }
    }
  }
}
</style>